package it.marcomondini.proximitytools.facades;

import it.marcomondini.proximitytools.MyApplication;
import it.marcomondini.proximitytools.SimpleLocationListener;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;

public class LocationFacade {
	
	private static final long POINT_RADIUS = 1; // in Meters
	private static final long PROX_ALERT_EXPIRATION = -1; 
	private static final String PROX_ALERT_INTENT = "it.marcomondini.proximitytools.ProximityAlert";

	
	private final Application applicationContext;
	private final LocationManager locationManager;
	
	private static volatile LocationFacade instance;
	
	private LocationFacade(){
		applicationContext = MyApplication.getInstance();
		locationManager = (LocationManager) applicationContext.getSystemService(Context.LOCATION_SERVICE);
	}
	
	public static LocationFacade instance(){
		if (instance == null){
			synchronized (LocationFacade.class) {
				if (instance == null){
					instance = new LocationFacade();
				}
			}
		}
		return instance;
	}
	
	
	public void addProximityAlert(Location location) {
		
        Intent intent = new Intent(PROX_ALERT_INTENT);
        PendingIntent proximityIntent = PendingIntent.getBroadcast(applicationContext, 0, intent, 0);
        locationManager.addProximityAlert(location.getLatitude(), location.getLongitude(), POINT_RADIUS, PROX_ALERT_EXPIRATION, proximityIntent);
    }
	
	public void registerNewLocation() {

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		locationManager.requestSingleUpdate(criteria, new SimpleLocationListener(){
			
			@Override
			public void onLocationChanged(Location location) {
				PreferencesFacade.saveReferencePoint(location);
				addProximityAlert(location);
				MyApplication.toastFactory("Registered proximity alert at location "+location.toString());
			}
			
		}, applicationContext.getMainLooper());
	}

	public void evaluateDistance() {
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		locationManager.requestSingleUpdate(criteria, new SimpleLocationListener(){
			
			@Override
			public void onLocationChanged(Location location) {
				Location referenceLocation = PreferencesFacade.getReferencePoint();
				if (referenceLocation == null){
					MyApplication.toastFactory("No reference location!");
					return;
				}
				float f = location.distanceTo(PreferencesFacade.getReferencePoint());
				MyApplication.toastFactory("Current distance to reference: "+f+"\n"+location);
			}
			
		}, applicationContext.getMainLooper());
		
	}
		
}
